package com.feiyuan.common.helper;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName SMSHelper
 * @Description 阿里云短信
 * @Author Xupf xupengfei131276@126.com
 * @Date 2021/9/30 9:45
 * @Version 1.0
 */
@Component
public class SMSHelper {

    private Logger logger = LoggerFactory.getLogger(SMSHelper.class);

    /**
     * 初始化配置对象Config。Config对象存放AccessKeyId、AccessKeySecret 、endpoint 等配置，Endpoint 如示例中的 dysmsapi.aliyuncs.com
     * @return
     * @throws Exception
     */
    private Client createClient() throws Exception {
        Config config = new Config();
        config.setAccessKeyId("LTAI5tEdsurQhHokT24UCz4G");
        config.setAccessKeySecret("Lz60ySfF3HzoZjXorlTfz992lZhjvY");
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 发送短信
     * @param phone 手机号
     * @param templateCode 短信模板
     * @param templateParam 短信模板中的参数
     */
    public Map<String, String> sendMessage(String phone, String templateCode, String templateParam) {
        Map<String, String> map = new HashMap<>();
        try {
            // 1.初始化配置对象Config,并实例化一个客户端
            Client client = this.createClient();

            // 2.创建对应API的Request
            SendSmsRequest request = new SendSmsRequest();
            // 手机号
            request.phoneNumbers = phone;
            // 签名
            request.signName = "飞飞聊天";
            // 短信模板
            request.templateCode = templateCode;
            // 短信模板变量对应的实际值。支持传入多个参数，示例：{"name":"张三","number":"1390000****"}。
            request.templateParam = templateParam;

            // 3.通过client对象获取对应request响应response
            SendSmsResponse response = client.sendSms(request);
            logger.info(new Gson().toJson(response.body));
            SendSmsResponseBody body = response.body;
            if (body.code.equals("OK")) {
                logger.info("phone is:[{}] templateCode is:[{}] send message success!", phone, templateCode);
                map.put("code", "OK");
                map.put("msg", "SUCCESS");
                return map;
            } else {
                logger.error("send message fail:{}", body.message);
                map.put("code", "FAIL");
                map.put("msg", body.message);
                return map;
            }
        } catch (Exception e) {
            logger.error("send message is error:", e.getMessage());
            map.put("code", "FAIL");
            map.put("msg", e.getMessage());
            return map;
        }
    }

}
